package com.starblink.store.discountproducts.ui

import android.content.res.ColorStateList
import android.graphics.drawable.RotateDrawable
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.utils.divider
import com.starblink.android.basic.brv.utils.linear
import com.starblink.android.basic.brv.utils.models
import com.starblink.android.basic.brv.utils.setup
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.FontUtil
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.basic.ext.load
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.sort.SortTypeEnum
import com.starblink.library.widget.sort.SortUtils
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.store.R
import com.starblink.store.StoreManager
import com.starblink.store.databinding.ActivityStoreDiscountProductsBinding
import com.starblink.store.databinding.CellSimpleProductCardHorizontalBinding
import razerdp.basepopup.BasePopupWindow

@Route(path = RoutePage.Store.PAGE_DISCOUNT_PRODUCTS)
class StoreDiscountProductsActivity :
    BaseTVMActivity<ActivityStoreDiscountProductsBinding, StoreDiscountProductsVM>() {

    // 店铺信息
    @Autowired(name = RoutePage.Store.STORE_INFO)
    @JvmField
    var storeInfo: MerchantWebVOF? = null

    override fun initViewBinding(): ActivityStoreDiscountProductsBinding =
        ActivityStoreDiscountProductsBinding.inflate(layoutInflater)

    override fun initData() {
        super.initData()
        viewModel.storeId = storeInfo?.id ?: ""
    }

    override fun initView() {
        super.initView()

        initViewTopBar()
        initViewSort()
        initViewRvDiscountProducts()
        initViewBottomRightBtns()

        // 初始化店铺信息UI
        storeInfo?.let { showStoreInfo(it) }
    }

    private fun initViewTopBar() {
        viewBinding.layoutTopBar.layoutSearch.click {
            // 点击搜索栏，跳转搜索页面
            navigationTo(RoutePage.Store.PAGE_SEARCH) {
                withString(RoutePage.Store.ID, storeInfo?.id)
            }
        }
    }

    private fun initViewSort() {
        // 价格排序和Discount排序互斥
        viewBinding.layoutSort.vSortPrice.setOnClickListener {
            // 显示排序弹窗
            SortUtils.showPriceSortPopup(
                context = mContext,
                alignView = viewBinding.layoutSort.root,
                sortView = viewBinding.layoutSort.vSortPrice,
                selectedSortType = viewModel.sortType,
            ) {
                // 选择排序选项后，重新加载数据
                if (it.sortType == viewModel.sortType) {
                    return@showPriceSortPopup
                }
                // 取消Discount排序
                viewBinding.layoutSort.vSortDiscount.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_text_secondary))
                viewBinding.layoutSort.vSortDiscount.typeface =
                    FontUtil.getTypeface(FontUtil.MONTSERRAT_MEDIUM)
                viewBinding.layoutSort.vSortDiscount.icon =
                    CommUtils.getDrawable(R.drawable.ic_sort_discount_normal)

                // Price排序设置为选中
                viewBinding.layoutSort.vSortPrice.text = it.text
                viewBinding.layoutSort.vSortPrice.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_text_primary))
                viewBinding.layoutSort.vSortPrice.typeface =
                    FontUtil.getTypeface(FontUtil.MONTSERRAT_SEMIBOLD)
                viewBinding.layoutSort.vSortPrice.iconTint =
                    ColorStateList.valueOf(color(com.starblink.basic.style.R.color.gu_text_primary))

                viewModel.sortType = it.sortType
                viewBinding.page.showLoading(refresh = true)
            }
        }

        viewBinding.layoutSort.vSortDiscount.setOnClickListener {
            if (viewModel.sortType == SortTypeEnum.DISCOUNT_H2L) {
                // 从H2L变为L2H
                viewModel.sortType = SortTypeEnum.DISCOUNT_L2H
                viewBinding.layoutSort.vSortDiscount.icon =
                    CommUtils.getDrawable(R.drawable.ic_sort_discount_l2h)
            } else {
                // 从L2H变为H2L,或者从normal变为H2L
                viewModel.sortType = SortTypeEnum.DISCOUNT_H2L
                viewBinding.layoutSort.vSortDiscount.icon =
                    CommUtils.getDrawable(R.drawable.ic_sort_discount_h2l)
                viewBinding.layoutSort.vSortDiscount.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_text_primary))
                viewBinding.layoutSort.vSortDiscount.typeface =
                    FontUtil.getTypeface(FontUtil.MONTSERRAT_SEMIBOLD)
            }
            // 取消Price排序
            viewBinding.layoutSort.vSortPrice.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_text_secondary))
            viewBinding.layoutSort.vSortPrice.typeface =
                FontUtil.getTypeface(FontUtil.MONTSERRAT_MEDIUM)
            viewBinding.layoutSort.vSortPrice.iconTint =
                ColorStateList.valueOf(color(com.starblink.basic.style.R.color.gu_text_secondary))

            viewBinding.page.showLoading(refresh = true)
        }
    }

    private fun initViewRvDiscountProducts() {
        viewBinding.rv.linear().divider {
            setDrawable(com.starblink.basic.style.R.drawable.sp_divider_horizontal1)
        }.setup {
            // 商品卡片
            addType<ProductF, CellSimpleProductCardHorizontalBinding>(it)

            onBind {
                val viewBinding = getBinding<CellSimpleProductCardHorizontalBinding>()
                val model = getModel<ProductF>()

                viewBinding.card.bindProduct(
                    activity = this@StoreDiscountProductsActivity,
                    product = model,
                    position = layoutPosition,
                    trackPage = SpmPageDef.StoreDiscountProductPage,
                    trackPageForComparePriceDialog = SpmPageDef.StoreDiscountProductComparePriceDialog,
                )
            }
        }

//        viewBinding.page.onLoading {
//            val ll = findViewById<LinearLayout>(com.starblink.basic.style.R.id.ll_loading)
//            ll.updateLayoutParams<ViewGroup.LayoutParams> {
//                height = 400.dp
//            }
//        }

        viewBinding.page.onRefresh {
            viewModel.loadSaleProducts(refresh = true)
        }
        viewBinding.page.onLoadMore {
            viewModel.loadSaleProducts(refresh = false)
        }
    }

    private fun initViewBottomRightBtns() {
        // 点击心愿单按钮，跳转到首页心愿单
        viewBinding.vWishList.setOnClickListener {
            FlowBus.intFlowBusNotify(FlowConst.WISH_INDEX_CHANGE, 3)
        }
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.listResponseLD.observe(this) {
            if (viewBinding.rv.models.isNullOrEmpty() || it.refresh) {
                // 刷新或页面销毁恢复
                // it.totalList必须使用ArrayList包裹一层，否则再次刷新不会显示新数据！！！
                viewBinding.page.addData(ArrayList(it.totalList)) {
                    it.totalList.isNotEmpty()
                }
            } else {
                // 加载更多
                viewBinding.page.addData(it.pageList) {
                    it.pageList.isNotEmpty()
                }
            }
        }
        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    viewBinding.page.showError()
                }
            }
        }

        initEvents()
    }

    private fun initEvents() {
        // 事件处理：关注店铺事件
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) { event ->
            if (storeInfo == null || event.id == null) {
                return@register
            }

            FlowCountDownTimer(time = 1).start(
                callBack = {},
                onFinish = {
                    if (event.id == storeInfo!!.id && event.followed != storeInfo!!.subOrNot) {
                        StoreManager.refreshFollowData(
                            storeInfo!!,
                            viewBinding.layoutStoreInfo
                        )
                    }
                })
        }
    }

    override fun initLoad() {
        super.initLoad()
        viewBinding.page.showLoading(refresh = true)
    }

    private fun showStoreInfo(merchant: MerchantWebVOF) {
        if (merchant.logo.isNullOrEmpty()) {
            StoreManager.showStoreTextIcon(merchant, viewBinding.layoutStoreInfo)
        } else {
            viewBinding.layoutStoreInfo.ivStoreIcon.load(merchant.logo, errorCall = {
                StoreManager.showStoreTextIcon(merchant, viewBinding.layoutStoreInfo)
            })
        }

        viewBinding.layoutStoreInfo.tvTitle.text = merchant.merchantName
        viewBinding.layoutStoreInfo.ivStoreIcon.click {
            StoreManager.navigationToStoreWebPage(merchant)
        }
        viewBinding.layoutStoreInfo.tvTitle.click {
            StoreManager.navigationToStoreWebPage(merchant)
        }

        viewBinding.layoutStoreInfo.tvSubscribers.text = "${merchant.subNum} Followers"
        viewBinding.layoutStoreInfo.tvSubscribers.visible()

        StoreManager.setFollowState(merchant.subOrNot, merchant.subNum, viewBinding.layoutStoreInfo)
        viewBinding.layoutStoreInfo.vFollow.run {
            click {
                StoreManager.followStore(
                    merchant,
                    mActivity,
                    lifecycleScope,
                    viewBinding.layoutStoreInfo
                )
            }
        }
    }
}